package work.util.data.io;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;

public class ManipFile
{
	
	public static void createIfNotExist(String dirPath)
	{
		File file = new File(dirPath);
		if (!file.exists())
			file.mkdirs();
	}

	public static void saveContent(String fileName, String content)
	{
		FileWriter writer = null;
		try
		{
			writer = new FileWriter(fileName, false);
			writer.write(content, 0, content.length());
		}
		catch (IOException ex)
		{
			ex.printStackTrace();
		}
		finally
		{
			if (writer != null)
			{
				try
				{
					writer.close();
				}
				catch (IOException e)
				{
					e.printStackTrace();
				}
			}
		}
	}

	public static String getContent(String fileName)
	{
		StringBuffer c = new StringBuffer();
		File file = new File(fileName);
		if (file.exists())
		{
			Scanner scanner = null;
			try
			{
				scanner = new Scanner(file);
				while (scanner.hasNextLine())
				{
					String line = scanner.nextLine();
					c.append(line + "\n");
				}
			}
			catch (FileNotFoundException e)
			{
				e.printStackTrace();
			}
			finally
			{
				scanner.close();
			}
		}
		return c.toString();
	}

	static public boolean deleteDirectory(File path)
	{
		boolean resultat = true;

		if (path.exists())
		{
			File[] files = path.listFiles();
			for (int i = 0; i < files.length; i++)
			{
				if (files[i].isDirectory())
				{
					resultat &= deleteDirectory(files[i]);
				}
				else
				{
					resultat &= files[i].delete();
				}
			}
		}
		resultat &= path.delete();
		return (resultat);
	}
}
